<?php
/* --------------------------------------------------------------
   mobile.php 2011-12-22
   Gambio GmbH
   http://www.gambio.de
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

define("V_1_0","1.0");
define("CURRENT_VERSION","1.0");
define("GET_ORDERS","getOrders");
define("GET_DETAILS","getDetails");  
define("GET_STATS","getStats");
define("GET_ONLINE_DATA","getOnlineData");
define("DATA_TYPE_GUESTS","Guests");
define("DATA_TYPE_CUSTOMERS","Customers");
define("GET_CART_DATA","getCartData"); 
define("GET_NEWS",'getNews');
define("GET_SCRIPT_VERSION",'getScriptVersion');

require('includes/application_top.php'); 
require(DIR_FS_INC. 'xtc_get_products.inc.php');
require(DIR_FS_ADMIN . 'gm/classes/GMStart.php');


if(isset($_POST)){
  
  $action     = xtc_db_input($_POST['action']);
  $lastUpdate = xtc_db_input($_POST['lastUpdate']);
  $order_id   = xtc_db_input($_POST['order_id']);
  $version    = xtc_db_input($_POST['use_script_version']);
  $data_typ   = xtc_db_input($_POST['data_type']);
  $cust_id	  = xtc_db_input($_POST['customer_id']);
  $session_id = xtc_db_input($_POST['session_id']);
  
  if($action == GET_SCRIPT_VERSION){
  	getScriptVersion();
  }

  if($version == V_1_0){
    if($action == GET_ORDERS){
      getOrders($lastUpdate);
    }else if($action == GET_DETAILS){
      getOrderDetails($order_id);
    }else if($action == GET_STATS){
      getStats();
    }else if($action == GET_ONLINE_DATA){
      getOnlineData();
    }else if($action == GET_CART_DATA){
      getUserCartData($session_id);
    }else if($action == GET_NEWS){
      getNewsUrl();
    }
  }
}  


function getScriptVersion(){
	$response = array('VERSION'=>CURRENT_VERSION);
    echo json_encode($response);
}
  
  
//===== functions for V_1_0 ============
function getOrderDetails($order_id){
		
		
 $sql = "SELECT O.CUSTOMERS_ID, O.CUSTOMERS_NAME, O.CUSTOMERS_COMPANY, O.ORDERS_ID, O.CUSTOMERS_ADDRESS_FORMAT_ID, O.CURRENCY,
 O.CUSTOMERS_STREET_ADDRESS, O.CUSTOMERS_CITY, O.CUSTOMERS_POSTCODE, O.CUSTOMERS_STATE, O.CUSTOMERS_EMAIL_ADDRESS, O.CUSTOMERS_TELEPHONE,
 O.DELIVERY_NAME, O.DELIVERY_COMPANY, O.DELIVERY_ADDRESS_FORMAT_ID, O.DELIVERY_STREET_ADDRESS, O.DELIVERY_CITY, O.DELIVERY_POSTCODE, O.DELIVERY_STATE, 
 O.DELIVERY_COUNTRY, O.DELIVERY_COUNTRY_ISO_CODE_2, O.BILLING_NAME, BILLING_COMPANY, O.BILLING_ADDRESS_FORMAT_ID, O.BILLING_STREET_ADDRESS, 
 O.BILLING_CITY, O.BILLING_POSTCODE, O.BILLING_COUNTRY, O.BILLING_COUNTRY_ISO_CODE_2, DATE_FORMAT( O.DATE_PURCHASED, '%d.%m.%Y %H:%i:%s' ) AS ORDER_DATE,
 DATE_FORMAT( O.LAST_MODIFIED, '%d.%m.%Y %H:%i:%s' ) AS MODIFIED, ST.ORDERS_STATUS_NAME AS ORDER_STATE,
 (SELECT COUNT(CUSTOMERS_NAME) FROM orders AS O, orders_status AS ST WHERE ST.ORDERS_STATUS_ID = O.ORDERS_STATUS AND CUSTOMERS_ID = O.CUSTOMERS_ID) AS AMOUNT_ORDERS
 FROM orders AS O, orders_status AS ST
 WHERE O.ORDERS_ID = $order_id AND O.ORDERS_STATUS = ST.ORDERS_STATUS_ID AND ST.LANGUAGE_ID =".$_SESSION['languages_id'];
    
 $order_data  = xtc_db_query($sql);

 $sql2 = "SELECT OP.PRODUCTS_MODEL, OP.PRODUCTS_NAME, OP.PRODUCTS_PRICE, OP.PRODUCTS_TAX, OP.FINAL_PRICE, OP.PRODUCTS_QUANTITY,
 (SELECT VALUE FROM orders_total WHERE CLASS = 'OT_SHIPPING' AND ORDERS_ID = OP.ORDERS_ID) AS ORDER_SHIPPING,
 (SELECT VALUE FROM orders_total WHERE CLASS = 'OT_TOTAL'AND ORDERS_ID = OP.ORDERS_ID) AS ORDER_TOTAL
 FROM orders_products AS OP 
 WHERE OP.ORDERS_ID = $order_id;";

 $order_items = xtc_db_query($sql2);
 
  $details = array();
  while($orderDataRow = xtc_db_fetch_array($order_data)){
  
    $items = array();
    $shipping; $total;
    while($itemData = xtc_db_fetch_array($order_items)){
      $item  = array(
      'M'   => $itemData['PRODUCTS_MODEL'],
      'N'   => $itemData['PRODUCTS_NAME'],
      'P'   => $itemData['PRODUCTS_PRICE'],
      'Q'   => $itemData['PRODUCTS_QUANTITY'],
      'T'   => $itemData['PRODUCTS_TAX'],
      'F'   => $itemData['FINAL_PRICE']);
      
      $shipping = $itemData['ORDER_SHIPPING'];
      $total    = $itemData['ORDER_TOTAL'];
      array_push($items,$item);
    }
     
    
    $details = array('CID'   => $orderDataRow['CUSTOMERS_ID'],
    'N'     	=> $orderDataRow['CUSTOMERS_NAME'],
    'CO'    	=> $orderDataRow['CUSTOMERS_COMPANY'],
    'OID'   	=> $orderDataRow['ORDERS_ID'],
    'CAF'   	=> $orderDataRow['CUSTOMERS_ADDRESS_FORMAT_ID'],
    'CS'    	=> $orderDataRow['CUSTOMERS_STREET_ADDRESS'],
    'CC'    	=> $orderDataRow['CUSTOMERS_CITY'],
    'CP'    	=> $orderDataRow['CUSTOMERS_POSTCODE'],
    'CST'   	=> $orderDataRow['CUSTOMERS_STATE'],
    'CEA'   	=> $orderDataRow['CUSTOMERS_EMAIL_ADDRESS'], 
    'CTEL'  	=> $orderDataRow['CUSTOMERS_TELEPHONE'],
    'DELAF' 	=> $orderDataRow['DELIVERY_ADDRESS_FORMAT_ID'],
    'DELN'  	=> $orderDataRow['DELIVERY_NAME'],
    'DELCO' 	=> $orderDataRow['DELIVERY_COMPANY'],
    'DELS'  	=> $orderDataRow['DELIVERY_STREET_ADDRESS'],
    'DELC'  	=> $orderDataRow['DELIVERY_CITY'],
    'DELP'  	=> $orderDataRow['DELIVERY_POSTCODE'],
    'DELCON'	=> $orderDataRow['DELIVERY_COUNTRY'],
    'DELCC' 	=> $orderDataRow['DELIVERY_COUNTRY_ISO_CODE_2'],
    'BILLAF'	=> $orderDataRow['BILLING_ADDRESS_FORMAT_ID'],
    'BILLN' 	=> $orderDataRow['BILLING_NAME'],
    'BILLCO'	=> $orderDataRow['BILLING_COMPANY'],
    'BILLA' 	=> $orderDataRow['BILLING_STREET_ADDRESS'],
    'BILLC' 	=> $orderDataRow['BILLING_CITY'],
    'BILLP' 	=> $orderDataRow['BILLING_POSTCODE'],
    'BILLCON' 	=> $orderDataRow['BILLING_COUNTRY'],
    'BILLCC'	=> $orderDataRow['BILLING_COUNTRY_ISO_CODE_2'],
    'AMOUNT'	=> $orderDataRow['AMOUNT_ORDERS'],
    'STATE' 	=> $orderDataRow['ORDER_STATE'],
    'DATE'  	=> $orderDataRow['ORDER_DATE'],
    'MODIFIED'	=> $orderDataRow['MODIFIED'],
    'ITEMS' 	=> $items,
    'SHIP'  	=> $shipping,
    'TOTAL' 	=> $total,
	'CURRENCY'	=> $orderDataRow['CURRENCY']);
	
	 $response = array('DETAILS'=>$details);
  	 echo json_encode($response);
  }
}
  
  
function getOrders($last_update){
 
  $FILTER = "";
  if(isset($last_update) && preg_match("/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/",$last_update)){
    $FILTER .= " and (O.DATE_PURCHASED > '$last_update' 
    OR O.LAST_MODIFIED > '$last_update')";
  }
  
 $test = "SELECT DISTINCT O.ORDERS_ID, O.CUSTOMERS_ID, O.CUSTOMERS_NAME, O.CURRENCY, ST.ORDERS_STATUS_ID AS ORDER_STATE_ID,
  O.CUSTOMERS_EMAIL_ADDRESS AS CUSTOMERS_EMAIL, DATE_FORMAT(O.DATE_PURCHASED,'%d.%m.%Y %H:%i:%s') AS ORDER_DATE,
  ST.ORDERS_STATUS_NAME AS ORDER_STATE,
  (SELECT VALUE FROM orders_total AS OT WHERE O.ORDERS_ID = OT.ORDERS_ID AND CLASS='OT_TOTAL') AS ORDER_TOTAL,
  O.LAST_MODIFIED FROM orders AS O, orders_status AS ST WHERE ST.ORDERS_STATUS_ID = O.ORDERS_STATUS
  AND ST.LANGUAGE_ID = ".$_SESSION['languages_id']." $FILTER ORDER BY O.DATE_PURCHASED DESC;";

  $order_data = xtc_db_query($test);
  
  $orders = array();
  while($orderDataRow =  xtc_db_fetch_array($order_data)){
    $order = array('OID' => $orderDataRow['ORDERS_ID'],
    'CID' => $orderDataRow['CUSTOMERS_ID'],
    'N'   => $orderDataRow['CUSTOMERS_NAME'],
    'E'   => $orderDataRow['CUSTOMERS_EMAIL'],
    'D'   => $orderDataRow['ORDER_DATE'],
    'SID' => $orderDataRow['ORDER_STATE_ID'],
    'S'   => $orderDataRow['ORDER_STATE'],
    'C'   => $orderDataRow['CURRENCY'],
    'T'   => $orderDataRow['ORDER_TOTAL'],
    'M'   => $orderDataRow['LAST_MODIFIED']);
    array_push($orders,$order);
  }
    
  $response = array('ORDERS' => $orders);
  echo json_encode($response);
}
    
    
function getStats(){
  
  $gmStart       = new GMStart();
  $visits_today  = $gmStart->gm_rates['VISITORS']['TODAY'];
  $visits_yest   = $gmStart->gm_rates['VISITORS']['YESTERDAY'];
  $visits_diff   = $gmStart->gm_rates['VISITORS']['DIFFERENCE'];
    
  $orders_today  = $gmStart->gm_rates['ORDERS']['TODAY'];
  $orders_yest   = $gmStart->gm_rates['ORDERS']['YESTERDAY'];
  $orders_diff   = $gmStart->gm_rates['ORDERS']['DIFFERENCE'];
    
  $sales_today   = $gmStart->gm_rates['SALES']['TODAY'];
  $sales_yest    = $gmStart->gm_rates['SALES']['YESTERDAY'];
  $sales_diff    = $gmStart->gm_rates['SALES']['DIFFERENCE'];
  
  $hits_today    = $gmStart->gm_rates['HITS']['TODAY'];
  $hits_yest     = $gmStart->gm_rates['HITS']['YESTERDAY'];
  $hits_diff     = $gmStart->gm_rates['HITS']['DIFFERENCE'];
    
  $average_today = 0;
  if($orders_today > 0){
    $average_today = $orders_today/$sales_today;
  }
    
  $average_yest  = 0;
  if($average_yest > 0){
    $average_yest  = $orders_yest/$sales_today;
  }
    
  $result = array('VT' => $visits_today,
  'VY' => $visits_yest,
  'VD' => $visits_diff,
  'OT' => $orders_today,
  'OY' => $orders_yest, 
  'OD' => $orders_diff, 
  'ST' => $sales_today,
  'SY' => $sales_yest,
  'SD' => $sales_diff,
  'AT' => $average_today,
  'AY' => $average_yest,
  'HT' => $hits_today,
  'HY' => $hits_yest,
  'HD' => $hits_diff);
    
  $response = array('STATS' => $result);
  echo json_encode($response);
}


function getNewsUrl(){
	$gmStart   = new GMStart();
	$ping_host = $gmStart->ping_host;
	$ping_path = $gmStart->ping_path;
	$response  = array('NEWS_URL' => array('PING'=>$ping_host,'PATH'=>$ping_path));
	echo json_encode($response);
}
  
  
function getOnlineData(){
	$whos_online_query = xtc_db_query("select customer_id, full_name, ip_address, time_entry, time_last_click, last_page_url, session_id from ". TABLE_WHOS_ONLINE ." order by time_last_click desc");
	$entries = array();

  	while($row = xtc_db_fetch_array($whos_online_query)){
  		$user_session = getUserSessionById($row['session_id']);
    	$data = array(
    		'CID' => $row['customer_id'],
    		'CN'  => $row['full_name'],
    		'IP'  => $row['ip_address'],
    		'TE'  => $row['time_entry'],
    		'LA'  => $row['time_last_click'],
    		'LP'  => $row['last_page_url'],
    		'S'   => $row['session_id'],
    		'V'   => $user_session['cart']->total,
			'C'	  => $user_session['currency']
		);  
    	array_push($entries,$data);
  	}
	
	$cart_data 	= array('ONLINE_DATA'=>$entries);
	echo json_encode($cart_data);
}
  
  
function getUserCartData($session_id){
	$user_session = getUserSessionById($session_id);
	$products     = xtc_get_products($user_session);
	
	$items = array();
	foreach($products as $prod){
			
		$tx  = xtc_db_query("SELECT TAX_RATE FROM tax_rates WHERE TAX_RATES_ID = ".$prod['tax_class_id']);
		$tax = xtc_db_fetch_array($tx);
		
		$item  = array(
		'M'   => $prod['model'],
      	'N'   => $prod['name'],
      	'P'   => $prod['price'],
      	'Q'   => $prod['quantity']*1,
      	'T'   => (!empty($tax)) ? $tax['TAX_RATE']*1 : 0,
      	'F'   => $prod['final_price']);
		array_push($items,$item);
	}

	$response = array('DETAILS'=>array('ITEMS'=>$items,'SHIP'=>0,'TOTAL' => $user_session['cart']->total, 'CURRENCY'=>$user_session['currency']));
  	echo json_encode($response);
}


function getUserSessionById($session_id){
		
	$info 		  = $session_id;
	$session_data = null;
	if (STORE_SESSIONS == 'mysql') {
    	$session_data = xtc_db_query("select value from " . TABLE_SESSIONS ." WHERE sesskey = '" . $info . "'");
     	$session_data = xtc_db_fetch_array($session_data);
     	$session_data = trim($session_data['value']);
   	} else {
     	if ( (file_exists(xtc_session_save_path() . '/sess_' . $info)) && (filesize(xtc_session_save_path() . '/sess_' . $info) > 0) ) {
       		$session_data = file(xtc_session_save_path() . '/sess_' . $info);
       		$session_data = trim(implode('', $session_data));
     	}
   	}
	
	$user_session = unserialize_session_data($session_data);
	return $user_session;
}


require('includes/application_bottom.php');  
?>